package org.xyl.context;

import org.xyl.context.EntityRecognizer;
import java.util.*;

/**
 * 上下文融合器 - 负责融合多源上下文信息
 */
public class ContextFusion {
    
    private BusinessEntityContextProvider entityContextProvider;
    private RuntimeContextProvider runtimeContextProvider;
    private KnowledgeContextProvider knowledgeContextProvider;
    private UserRoleContextProvider roleContextProvider;
    
    public ContextFusion() {
        this.entityContextProvider = new BusinessEntityContextProvider();
        this.runtimeContextProvider = new RuntimeContextProvider();
        this.knowledgeContextProvider = new KnowledgeContextProvider();
        this.roleContextProvider = new UserRoleContextProvider();
    }
    
    /**
     * 融合上下文信息
     */
    public FusionResult fuse(ContextExtractionResult extractionResult) {
        // 获取提取结果中的信息
        String userQuery = extractionResult.getUserQuery();
        SessionContext sessionContext = extractionResult.getSessionContext();
        Map<String, List<String>> entities = extractionResult.getEntities();
        UserIntent intent = extractionResult.getIntent();
        
        // 获取业务实体上下文
        BusinessEntityContext entityContext = entityContextProvider.getBusinessEntityContext(entities);
        
        // 获取用户角色上下文
        UserRoleContext roleContext = roleContextProvider.getUserRoleContext(sessionContext);
        
        // 根据意图决定是否需要获取运行时上下文
        RuntimeContext runtimeContext = null;
        if (intent == UserIntent.DIAGNOSTIC && entities.containsKey(EntityRecognizer.ENTITY_DEVICE_ID)) {
            List<String> deviceIds = entities.get(EntityRecognizer.ENTITY_DEVICE_ID);
            if (!deviceIds.isEmpty()) {
                runtimeContext = runtimeContextProvider.getRuntimeContext(deviceIds.get(0));
            }
        }
        
        // 获取知识上下文
        KnowledgeContext knowledgeContext = knowledgeContextProvider.getKnowledgeContext(
            userQuery, entities, intent);
        
        return new FusionResult(
            userQuery, sessionContext, entityContext, roleContext, runtimeContext, knowledgeContext, intent
        );
    }
}